var watchlist = function(profile,callback){
    this.startup=null;
    this.settingpanel=null;
    this.operatemenu=null;
    this.core=null;
    this.tabmenu=null;
	var qslan=QS_Lang.watchlist;
	this.defualtMSView = qslan['intraday'];
	this.defaultViewID ='-2';
    this.operateMenuData_MSView = [{
        txt: this.defualtMSView,
        val: '-2',
        vid: '-2',
        type: "ratio"
    }, {
        txt: qslan['short'],
        val: '-3',
        vid: '-3',
        type: "ratio"
    }, {
        txt: qslan['extended'],
        val: '-1',
        vid: '-1',
        type: "ratio"
    }, {
        txt: qslan['portfolio'],
        val: '-4',
        vid: '-4',
        type: "ratio"
    }];
	this.callback={};
	$.extend(true,this.callback,callback);
    this.operateMenuData_MyView = [];
    this.layoutList = [{
        txt: qslan["list"],
        val: 'list'
    }, {
        txt: qslan["l&g"],
        val: 'listgroup'
    }, {
        txt: qslan["l&w"],
        val: 'listwrap'
    }, {
        txt: qslan["l,g&w"],
        val: 'listgroupwrap'
    }, {
        txt: qslan["heatmap"],
        val: 'heatmap'
    }];
    this.groupbyList = [{
        txt: qslan["ms_sector"],
        val: 'la03z'
    }, {
        txt: qslan["ms_industry"],
        val: 'st153'
    }, {
        txt: qslan["ms_exchange"],
        val: 'exch'
    }, {
        txt: qslan["ms_currency"],
        val: 'of028'
    }];
	this.staticValue={
		sumHeight:36,
		tabMenuHeight:28,
		minWidth:200,
		selectTabID:0
	};
    this.profile={
		isAPI:false,
        startup:true,
        setting:true,
        importtool:true,
		exporttool:true,
        contextmenu:true,
        editdialog:true,
        customview:true,
        operatemenu:true,
        isShowHideChecked:true,//show tabmenu
        hasSearch:false,
        openedList:[],
        currentId: 0,
        viewCount:6,//viewlist max count
        remove:false,
        isIncludeSummary:true,
        isShowSummary:false, //show summary
		settingPnCtn:null, // setting panel container
		fixHeight:true,
		showInvalidTicker:true,
		activeTab:0//default index of active tab in all "select tab"
    };
    $.extend(this.profile, profile);
};


watchlist.prototype = $.extend(false,typeof QSAPI_watchlist!='undefined'?QSAPI_watchlist:{},{
    _initGroupbyList:function(){
        if (this.profile.SNP_GICS) {
            this.groupbyList = this.groupbyList.concat([{
                txt: QS_Lang.watchlist["s&p_sector"],
                val: 'sta4n'
            }, {
                txt: QS_Lang.watchlist["s&p_industrygroup"],
                val: 'sta4j'
            }, {
                txt: QS_Lang.watchlist["s&p_industry"],
                val: 'sta4l'
            }]);
        };
    },
    clear:function(){
        for (var p in this) {
            if (!p || p == 'clear') {
                continue;
            }
            this[p] = null;
            delete this[p];
        }
    },
    init: function(containerId,profile,conCofig){  //conCofig:{settingPnCtn:settingPnCtn}
        var self = this;
		this.showLoading(true);
		if (profile.currentWatchlistlID || profile.currentPortfolioID) {
			profile.currentId = profile.currentWatchlistlID || profile.currentPortfolioID; //for old version watchlist
		}
		if(conCofig&&conCofig.settingPnCtn){
			this.profile.settingPnCtn = conCofig.settingPnCtn;
		}
		//for supporting default watchlist
		if ((!profile.openedList || profile.openedList.length < 1) && profile.currentId) { //build openedList if has currentId
			profile.openedList = [{
				id: profile.currentId
			}];
		}
		this.container=$('#' + containerId);
		if (typeof(this.setTitle) != "undefined" && profile.title && profile.title != '') {
			this.setTitle(profile.title);
		}
		$.extend(true, this.profile, profile);
		var html = '<div class="rtq-wl"><div class="rtq-wl-tab-wrap clearfix"><div class="rtq-wl-tab"></div><div class="wl-datagrid" id="gridctn_' + containerId + '"></div></div>';
		this.el = $(html).appendTo(this.container);   
		
		if(this.profile.isIncludeSummary){
			this.summaryObj = new WatchlistSummary(this.container,{},{
				onClickRefresh:function(){
					self.showSummary();
				}
			});
		}
		
		//datagrid callback
		var callbacks = {
			onRowRemove: function(id, row){
			
			},
			onRowDragStart: function(e, proxy, row){  // prevent the ticker is from the same component.
				proxy._cpnId = self.id;
			},
			onRowRearrange: function(row, insertbeforerow){  // when moving the row.
				if (!row||row.data.InvalidTicker || gData[row.data.gkey].type == 20 || gData[row.data.gkey].type == 3) {
					return;
				}
				QS_watchlistDataManager.moveHolding(self.profile.currentId, row.id, insertbeforerow.id);
			},
			onCellSort: function(cellkey, order){
			},
			onCellRearrange: function(cellkey, index){  //change the view(cols).
				if(self.profile.customview){
					QS_WatchListCustomView.updateView(self.profile.colsViewID, self.core.getColumnCfg());
				}
			},
			afterResizeCol: function(cellkey, w){  // change the view(the size of view).
				if(self.profile.customview){
					QS_WatchListCustomView.updateView(self.profile.colsViewID, self.core.getColumnCfg());
				}
			},
			onCellRemove: function(cellkey){
				if(self.profile.customview){
					QS_WatchListCustomView.updateView(self.profile.colsViewID, self.core.getColumnCfg());
				}
			},
			onRowDoubleClick: function(e, row){
				if (row.data.InvalidTicker || gData[row.data.gkey].type == 20 || gData[row.data.gkey].type == 3) {
					return;
				}
				workspaceManager.addTickerToUnLockWindow(self._getTickerOnRow(row));
			},
			onRowContextmenu: function(e, row){
				if (!self.profile.contextmenu || row.data.InvalidTicker|| gData[row.data.gkey].type == 3) {
					return;
				}
				var obj = {};
				obj.wsid = self.profile.currentId;
				obj.ticker = self._getTickerOnRow(row);
				obj.hid = row.id;
				obj.securityType = gData[row.data.gkey].mType;
				QS_watchlistContextMenu.setCallback(self._contextCallback());
				QS_watchlistContextMenu.openContextMenu(e, obj, false);
			},
			onRowSelected: function(e, row){
			},
			onScrollEnd: function(l, t){
			},
			afterRebindData: function(){  // after tickerList rebind data.
				if(self.profile.isIncludeSummary&&self.profile.isShowSummary){  
					self.showSummary();
				}
				self.hideLoading();
			},
			afterGroupDrop: function(){
				
			},
			onLoad: function(para){
				if(self.callback.onLoad){
					self.callback.onLoad({
						component: "watchlist",
						height: para.height+(self.profile.isShowSummary ? self.staticValue.sumHeight : 0)+(self.profile.isShowHideChecked? self.staticValue.tabMenuHeight : 0),
						width:para.width,
						minWidth : self.staticValue.minWidth
					});
					self.firstTag = false;
				}
			},
			onHeightChange: function(para){
				if(self.callback.onHeightChange){
					self.callback.onLoad({
						component: "watchlist",
						height: para.height+(self.profile.isShowSummary ? self.staticValue.sumHeight : 0)+(self.profile.isShowHideChecked? self.staticValue.tabMenuHeight : 0),
						width:para.width
					});
				}
			},
			afterDeleteWatchlist:function(wid){
				self._removeTabs(wid,true);
				if (self.profile.startup) {
					self.startup.refreshList();
				}
			},
			afterRenameWatchlist:function(wid,name){
				self._renameTab(wid,name);
			},
			afterSaveHoldings:function(wid, holdings){
				
			}
		};
		var coreprofile = {
			width: this.profile.width,
			height: this.profile.height - (this.profile.isShowSummary ? this.staticValue.sumHeight : 0)-(this.profile.isShowHideChecked?this.staticValue.tabMenuHeight:0),
			groupBy: this.profile.groupBy,
			remove:true,   // include the remove menu in ticker list.
			displayLayout: this.profile.displayLayout,
			sortCell: this.profile.sortCell, 
			autoHeight:!this.profile.fixHeight,
			isLPLUser: this.profile.isLPLUser,
			sortOrder: this.profile.sortOrder,
			showInvalidTicker:this.profile.showInvalidTicker
		}
		if(profile.tempCols&&profile.tempCols!=null){
			coreprofile.viewKey =  profile.tempCols;
		}
		//generate watchlist
		this.core = new watchlist_core(this.el.find('.wl-datagrid'), coreprofile, callbacks);
		//core as the really watchlist
		this.core.setID(this.id);//must include ID
		this.tickerValidation=new tickerValidation(0);
		this.tickerValidation.showAlert=false;
		this.core.setTickerValidation(this.tickerValidation);
		this._initGroupbyList();
		//generate the tabmenu
		this._buildTabMenu([]);
		//generate related component
		this._initAddons();
		var viewId = profile.colsViewID||Terminal.getConfig('WatchlistDefaultView')||this.defaultViewID;
		this.profile.colsViewID="";//reset the init value
		QS_watchlistDataManager.getPortfolioList(function(plist){
			QS_CustomViewManagement.getCustomviewList(function(){
				self._changeViewId(viewId,true,function(custom){
					if(self.profile.setting){
						var title=parseInt(viewId)<0?self._getDefaultWatchlistName(viewId):custom.data.title;
						self.settingpanel.updateCurrentView(title,"");
						if(self.profile.displayLayout=="heatmap"){
							self.settingpanel.disableView();
						}
					 }
					 if (self.profile.openedList.length > 0) {//bind tab menu
						self.tabmenu.reBindData(self.getTabData(self.profile.openedList));  // when bind the tabmenu data, it active one tab item.
					}else{  
						if (self.profile.startup) {
							self._startUpShow();
						}
					}
				});
			});
		});
    },
    _onStartUpBtnCallback: function(val, data, callback){ // handle the startup 
        var self = this;
        switch (val) {
            case 'new_wl': // new watchlist.
                Util.prompt(QS_Lang.text["watchlistinput"], function(value){ // vidate success.
                    var name = $.trim(value);
                    self.core.createWatchlist(name, 1, [], function(d){
                        self._insertTabitem(d.id, name);
						if (self.profile.startup) {
                            self.startup.refreshList();
                        }
                    });
                    
                }, {
                    validateMethod: function(value){
                        return self._validateInput(value);
                    }
                });
                break;
            case 'new_pl': // new portflio.
				QS_watchlistEditDialog.setCallback(self._editDialogCallback());
                QS_watchlistEditDialog.open({type: 0});
                break;
            case 'import_office': // import tickers from office or direct system.
            case 'import_direct':
                if (!QS_importDialog) {
                    QS_importDialog = new officePortfolio();
                }
                QS_importDialog.open(self, val.split('_')[1]);
                break;
            case 'import_manual': // import ticker to current watchlist by manual or copy from excel
            case 'excel':
                // var type = item.data.val;
				QS_watchlistImportor.callBack.reBindCaller(self);
				QS_watchlistImportor.open(val,{inCurrentList: false});
                break;
            case 'open': // open a existed watchlist under actived tab item.
            	var index = this.tabmenu.currentTab.index;
				this._removeTabitem(this.tabmenu.currentTab.id, false,index);// remove the start up tab item.
				this._insertTabitem(data.id, data.name,index);
                break;
            case 'open_tab': // open a existed watchlist in a new tab item
				this._insertTabitem(data.id, data.name);
                break;
            case 'open_win': // open a existed watchlist in a new watchlist.
                var pf = getDefaultProfileByType(0);
                pf.widget.currentId = data.id;
                setTimeout(function(){ //active the win
	               RtqDesktop.addModule(pf);
                }, 0);
                break;
            case 'rename': // rename the watchlist.
				self.core.reNameWatchlist(data.id,data.type);
                break;
            case 'edit': // edit the exsited watchlist.
                self._openEditDialog(data.id,data.type);
                break;
            case 'del': // delete the watchlist.
                self.core.deleteWatchlist(data.id, function(b){
					if (typeof(callback) == "function") {
						callback("del", b.op);
					}
                });
                break;
        }
    },
    _openEditDialog:function(id,type){
    	var self=this;
		self.showLoading(true);
        QS_watchlistDataManager.getHoldings(id, function(holdings){
        	var tickers = [], tickersMap = {}, ticker;
        	for (var i = 0; i < holdings.length; i++) {
				ticker = holdings[i].SecId || holdings[i].Ticker;
				if (!tickersMap[ticker]) {
					tickersMap[ticker] = true;
					tickers.push(ticker);
				}
			} 
			QS_watchlistEditDialog.setCallback(self._editDialogCallback());
			self.tValidation.showAlert = false;
			self.tValidation.checkTickers(tickers, function(o, t){
                QS_watchlistEditDialog.open({
                    id: id,
                    name: self._getWatchlistName(id),
                    type: type,
                    data: holdings
                });
                self.hideLoading();
            });
        });
    },
    _validateInput: function(title,showAlert){ // vildate the watchlist name inputted.
        title = $.trim(title);
		var showAlert=typeof showAlert=='undefined'?true:showAlert;
        if (!title || title.length < 1) {
            Util.message(QS_Lang.text["watchlistinput"]);
            return false;
        }
        if (typeof(QS_Validator) != "undefined" && !QS_Validator.test(title, 'name')) {
            return false;
        }
        if (title.length > this._maxTitleLength) {
            Util.message(QS_Lang.text["watchlisttitle"]);
            return false;
        }
        if (title == 'Untitled') {
            return false;
        }
        if (typeof(QS_watchlistDataManager) != "undefined" && QS_watchlistDataManager.checkWatchlistName(title) !== false) { // check the name 
            if (showAlert) {
				Util.message(QS_Lang.text["watchlisttitle2"]);
			}
            return false;
        }
        return true;
    },
	_editDialogCallback:function(){
		var self=this;
		var gridcallback = {
			createData: function(obj){
				self.core.createWatchlist(obj.name, obj.type, obj.data, function(data){
					var id = data.id;
					if (id&&(id > 0||isNaN(id))) {
						if (self.profile.startup) {
							self.startup.refreshList();
						}
						self._insertTabitem(id, obj.name);
						self.profile.currentId=id;
						self.refreshGrid();
					}
					
				});
			},
			createValidation:function(obj){
				return self._validateInput(obj.name);
			},
			saveData: function(obj){
				QS_watchlistDataManager.insertHoldings(obj.id, obj.newData, true);
				QS_watchlistDataManager.updateHoldings(obj.id, obj.ediData);
				QS_watchlistDataManager.deleteHoldings(obj.id, obj.delData);
				QS_watchlistDataManager.saveHoldings(obj.id);
			}
		};
		if (self.profile.contextmenu) {
			gridcallback.onRowContextmenu = function(e, obj){
				QS_watchlistContextMenu.setCallback(self._contextCallback());
				QS_watchlistContextMenu.openContextMenu(e, obj, true);
			}
		}
		return gridcallback;
	},
	_contextCallback:function(){
		var self=this;
		var callback={
			openContextMenuBefore: function(obj){
				if (QS_watchlistDataManager.getPermissionById(obj.wsid) != 0) {
					var holding = QS_watchlistDataManager.getHoldingByHoldId(obj.wsid, obj.hid);
					if (holding["Date"]) {
						QS_watchlistContextMenu.setChartStartDate(holding["Date"]);
					}
				}
				var operateMenuData_Sort = self.core.getSortColumns();
				var getlastSortCellKey = self.core.getlastSortCellKey();
				for (var i in operateMenuData_Sort) {
					operateMenuData_Sort[i].selected = operateMenuData_Sort[i].val == getlastSortCellKey;
				}
				QS_watchlistContextMenu.reBindSecondLevelMenu("sort", operateMenuData_Sort, 1);
			},
			onclick: function(item, obj){
				var profile = null,pval = item.parent != null?item.parent.data.val:null,val = item.data.val;
				if (pval != null && pval == "1") { // open chart window.
					profile = getDefaultProfileByType("1");
					profile.widget.chartStyle = item.data.val;
					var chartDate = QS_watchlistContextMenu.getChartStartDate();
					if (chartDate != null) {
						profile.widget.zRange = 11;
						profile.widget.startDate = chartDate;
					}
					else {
						profile.widget.zRange = 3;
					}
					profile.widget.securityType = obj.securityType;
					workspaceManager.addWidgetToCurrentWs("1", obj.ticker, profile);
				}else if (pval != null && pval == "9" && val != '9') { // quick take under the security research.
					profile = getDefaultProfileByType(3);
					profile.widget.title = item.data.txt;
					profile.widget.tab = item.data.qtTab;
					profile.widget.showTab = item.data.showTab === true ? true : false;
					profile.widget.ticker = obj.ticker;
					workspaceManager.addWidgetToCurrentWs(3, obj.ticker, profile);
				}else if (val == '4') { // alert
					if (typeof workspaceManager != 'undefined') {
						workspaceManager.openAlertSetting();
					}
				}else if (val == 'delete') {
					if (QS_watchlistContextMenu.getIsEditDialog() && self.profile.editdialog) {
						QS_watchlistEditDialog.removeRow(obj.hid);
					}else {
						self.core.removeRow(obj.hid);
					}
				}else if (pval!=null&&pval == 'sort') {
					self.core.sort(val);
				}else if(val=='cons'){
						var gkey=gIdMap[obj.ticker];
						var data = gData[gkey||obj.ticker];
						if(data){
							self.showLoading(true);
							var sid=data["secId"];
							if (!sid || $.trim(sid) == "") {
								Util.message(QS_Lang.text["noconstituents"]);
								self.hideLoading();
							}else {
								var name=data["clientTicker"];
								if (!self._validateInput(name,false)) {//exist this watchlist
									var pfid = QS_watchlistDataManager.getWatchlistID(name);
									self._removeTabs(pfid,false);
								}
								QS_watchlistDataManager.getConstituents(sid, function(odata){
									if (odata) {
										self.openConstituents(name, odata);
									}
									else {
										Util.message(QS_Lang.text["noconstituents"]);
										self.hideLoading();
									}
								});
							}
						}
				}else{ // orther widgets.
					profile = getDefaultProfileByType(item.data.val);
					workspaceManager.addWidgetToCurrentWs(item.data.val, obj.ticker, profile);
				}
			}
		};
		return callback;
	},
	_getDefaultWatchlistName:function(id){
		for(var i=0,l=this.operateMenuData_MSView .length;i<l;i++){
			if(this.operateMenuData_MSView[i].val==id){
				return this.operateMenuData_MSView[i].txt;
			}
		}
		return "";
	},
    _initAddons: function(){
        var self = this;
		if (this.hasSearch) {
            this.initAutoComplete();
        }
        if (this.profile.startup) {
            this.startup = new Watchlist_StartUp(this.el, {
                contextMenu: true,
                contextMenuContainer:$("body")
            }); // contextMenuContainer 
            this.startup.onExcute = function(val, data, callback){
                self._onStartUpBtnCallback(val, data, callback);
            }
            this.startup.hide();
			/*
            this.el.find('.rtq-wl-tab-wrap .add-btn').click(function(e){
                self._startUpShow();
            });
			*/
        }else{
			/*this.el.find('.rtq-wl-tab-wrap .add-btn').hide();*/
		}
        if (this.profile.operatemenu) {
            this._createOperateMenu();
        }
        
        if (this.profile.editdialog&&!QS_watchlistEditDialog) {//global Object
			QS_watchlistEditDialog = new watchlistEditDialog(null, {}, {});
        }
        if (this.profile.contextmenu&&!QS_watchlistContextMenu) {
            QS_watchlistContextMenu = new watchlistContextMenu();
        }
		if (this.profile.customview&&!QS_WatchListCustomView&&!this.profile.isAPI) {
            QS_WatchListCustomView = new WatchListCustomView({
            	onViewUpdate:function(id,name){//when update/delete a customview call

            	},
            	onViewCreate:function(id,name){//when add a customview call

            	}
            });
        }
        if (this.profile.setting) {
            var groupByList = [{
                txt: 'Currency',
                val: 'currency'
            }, {
                txt: 'Mstar Industry',
                val: 'st153'
            }];
            /*
             [{
             txt: 'Mstar Sector',
             val: 'la03z'
             }, {
             txt: 'Mstar Industry',
             val: 'st153'
             }, {
             txt: 'Exchange',
             val: 'exch'
             }, {
             txt: 'Mstar Fund Category',
             val: 'of028'
             }];
             if (hasSNP_GICS == true) {
             groupByList = groupByList.concat([{
             txt: 'S&P Sector',
             val: 'sta4n'
             }, {
             txt: 'S&P Industry Group',
             val: 'sta4j'
             }, {
             txt: 'S&P Industry',
             val: 'sta4l'
             }]);
             };
             */
            this.settingpanel = new WatchListSettingMenu(this.profile.settingPnCtn || this.el, {
                defViewList: this.operateMenuData_MSView,
                layoutList: this.layoutList,
                displayLayout: this.core.getDisplayLayout(),  // the selected layout type.
                groupByList: this.groupbyList,
                groupBy: this.profile.groupBy,
                isShowSummary: this.profile.isShowSummary,
                isCheckAutoAddSymbol:this.profile.windowConfig?this.profile.windowConfig.isCheckAutoAddSymbol:false,
                isCheckLock: this.profile.windowConfig?this.profile.windowConfig.isCheckLock:false,
                isSelectAuto: this.profile.windowConfig?this.profile.windowConfig.isSelectAuto:false,
                isSelectTabName: this.profile.windowConfig?this.profile.windowConfig.isSelectTabName:false, 
                isShowHideChecked: this.profile.isShowHideChecked,
                currentViewName: this.defualtMSView
            }, {
                onTitleChange: function(title){
                    if (title == '') {
                        self.setTitle(self._getWatchlistName(self.profile.currentId));
                    }
                    else {
                        self.setTitle(title);
                    }
                },
                onLock: function(isLock){
                    self.lock = isLock;
                },
                onShowHideCheck: function(selected, flag){  // show tab menu to hide it.
                    self._onShowHide(selected, flag);
                },
                onClickStartUp: function(){
                    self._startUpShow();
                },  
                onShowSummaryClick: function(isSelected){  // show or hide summary component.
                    if(isSelected)self.showSummary();
                    else self.hideSummary();
                },
                onImportClick: function(productCode){
                },
                onChangeDisplayDDL: function(displayType){
                    var oldviewtype = self.core.getDisplayLayout();
                    if(displayType=="listgroup"||displayType=="listgroupwrap"){
                        self.groupBy('la03z', function(){   // set a default group by field
                            self.changeViewType(displayType);
                        });
                    }else{
                        self.changeViewType(displayType);
                        if(self.profile.operatemenu&&(displayType == "heatmap" || oldviewtype == "heatmap")){
							var data = self._getSortMenuData();
							self.operatemenu.reBindSecondLevelMenu("sort",data,1);
                        }
                    }
                },
                onChangeGroupDDL: function(groupBy){
                    QS_watchlistDataManager.LPLGroup(self.profile.currentId, groupBy, function(groupBy){
                        self.groupBy(groupBy,null);
                    });
                },
                onViewAction: function(action, viewId,callback){//action: /select/add/edit/delete
                    switch (action) {
                        case 'new':
                            QS_WatchListCustomView.create(null,function(viewId,name){
                                self._changeViewId(viewId,false,function(custom){
                                    if(self.profile.setting&&custom.id==viewId){
                                        self.settingpanel.updateCurrentView(name,"");
                                     }
                                }); // after new view ,update the view of this watchlist.
                            });// create
                            break;
                        case 'select':
                            self._changeViewId(viewId,false,function(custom){
								if(self.profile.setting&&custom.id==viewId){
									var title=parseInt(viewId)<0?self._getDefaultWatchlistName(viewId):custom.data.title;
									self.settingpanel.updateCurrentView(title,"");
								 }
							});
                            break;
                        case 'edit':
                            //self.editColsViewPN(txt, viewId);
                            QS_CustomViewManagement.getCustomviewData(viewId, function(custom){
								if(custom.id==viewId){
									QS_WatchListCustomView.edit({
										title: custom.data.title,
										cols: custom.data.cols,
										id: custom.id
									});
								}else{
									Util.message(QS_Lang.text["watchlistcvfailed"]);
								}
                            });
                            break;
                        case 'delete':
                            QS_CustomViewManagement.deleteCustomView(viewId, function(d){
                                if (d) {
                                    QS_CustomViewManagement.sync(viewId, true);
                                    QS_CustomViewManagement.getCustomviewList(function(o){
                                        self.settingpanel.createViewMenu(o);
										if(callback){
											var list=[];
											for (var i = 0; i < o.length; i++) {
												list.push({
													text: o[i].title,
													cmd: o[i].id
												});
											}
											callback(list);
										}
                                    });
                                }
                            });
                            break;
                    }
                }
            });
        }
        if (this.profile.importtool&&!QS_watchlistImportor) {
			var cfg = {
				maxTicker: QS_watchlistDataManager.getMaxTickers()
			}, callback = {
				caller: self,
				onImportToNewList: function(list, name){
					
					var own = this;
					self.core.createWatchlist(name, QSPC.moduleConfigs[0].isDotComUser?'1':'0', list, function(args){
						var pid = args["id"];
						QS_watchlistDataManager.saveHoldings(pid,function(){
							self._insertTabitem(pid, name);
							if (own.caller.profile.startup) {
								own.caller.startup.refreshList();
							}
						});
					});
				},
				onImportToCurrentList: function(list, portfolioId){
					QS_watchlistDataManager.insertHoldings(portfolioId, list, true);
					QS_watchlistDataManager.saveHoldings(portfolioId,null);
					this.caller.refreshGrid();
				},
				invokeCallBackByName: function(method, parameter){
					this[method].apply(this, parameter);
				},
				reBindCaller: function(wachlistObj){
					this.caller = wachlistObj;
				}
			};
			QS_watchlistImportor = new wachlistImport(cfg, callback);
		}
		
		if(this.profile.exporttool&&!QS_watchlistDataExporter){
			 QS_watchlistDataExporter = new watchlistDataExporter();
		}
    },
    _changeViewId:function(viewId,update,callback){
		var updateWl=update||false;
        if(this.profile.colsViewID != viewId){
            var self = this;
            QS_CustomViewManagement.regCustomview(this,viewId);
            this.profile.colsViewID = viewId;
            QS_CustomViewManagement.getCustomviewData(viewId, function(custom){
				if(custom.id==viewId||updateWl){
					self.profile.colsViewID = custom.id;
					self.core.setColumns(custom.data.cols);
					QS_CustomViewManagement.regCustomview(this,custom.id);
					if(self.profile.operatemenu){
						var data = self._getSortMenuData();
						self.operatemenu.reBindSecondLevelMenu("sort",data,1);
					}
				}else{
					 Util.message(QS_Lang.text["watchlistcvfailed"]);
				}
                if(typeof callback == "function"){
                    callback(custom);
                }
            });
        }else{
			if(typeof callback == "function"){
				callback({id:viewId,data:{}});
			}
		}
    },
    onViewDelete:function(deleteViewId){  // sync with the view has deleted. open the default view -2.
        var self = this,defaultId=Terminal.getConfig('WatchlistDefaultView')||this.defaultViewID;
        this._changeViewId(defaultId,true,function(customview){
            if(self.profile.setting){
            	var title=parseInt(defaultId)<0?self._getDefaultWatchlistName(defaultId):custom.data.title;
                self.settingpanel.updateCurrentView(title,"");
             }
        });
    },
    onViewUpdate:function(viewID,view){
        var self = this;
        QS_CustomViewManagement.getCustomviewData(viewID, function(custom){
			if(custom.id==viewID){
				self.core.setColumns(view||custom.data.cols);
				if(self.profile.operatemenu){
					var data = self._getSortMenuData();
					self.operatemenu.reBindSecondLevelMenu("sort",data,1);
				}
			}
        });
    },
	changeViewType:function(v){
		this.core.changeViewType(v);
	},
	groupBy:function(group,callback){
		this.core.groupBy(group,callback);
	},
	_onShowHide: function(v,flag){
        var firstflag=false;
        this.el.find('.rtq-wl-tab-wrap .rtq-wl-tab')[0].style.display = v ? "" : "none";
        //this.el.find('.rtq-wl-tab-wrap .add-btn')[0].style.display = v ? "" : "none";
        this.profile.isShowHideChecked = v;
        if(typeof flag!='undefined') firstflag=flag;
        if (!firstflag) {
            this.changeOutSize();
        }
    },
    _startUpShow: function(){
        this._insertTabitem(this.staticValue.selectTabID, QS_Lang.watchlist["select"]);
    },
	showSummary:function(){
		this.profile.isShowSummary = true;
		if(this.core){
	        var currentid = this.core.getCurrentId();
	        if(this.profile.isIncludeSummary&&typeof currentid != "undefined"&&!this._displayStartup){  // not show start up.
	            var self = this;
	            if(!self._displaySummary){ // switch from invision to vision need change the outsize.
	                self.changeOutSize();
	            }
	            this.summaryObj.show(currentid,this.core.getIDs(),function(){
	                self._displaySummary = true;
	            })
	     
	        }
	    }
    }, 
    hideSummary:function(){
        if(this.profile.isIncludeSummary&&this.core.getCurrentId()!=this.staticValue.selectTabID){
            this.profile.isShowSummary = false;
            if(this._displaySummary){ // switch from invision to vision need change the outsize.
                this.changeOutSize();
            }
            this.summaryObj.hide();
            this._displaySummary = false;
        }
    },
    _getTickerOnRow: function(row){
        var ticker;
        var data = gData[row.data.gkey];
        if (row.data.InvalidTicker) {
            return null;
        }
        if (data && data["performanceId"] && data.type != 'FUTURE') {
            ticker = data["performanceId"];
        }else if (data.exch && data.ticker && data.type != 'FUTURE') {
            ticker = data.exch + ':' + data.ticker;
        }
        else {
            return null;
        }
        return ticker;
    },
    _getWatchlistName: function(id){ // this.staticValue.selectTabID: startup
        return id == this.staticValue.selectTabID ? QS_Lang.watchlist["startupname"] : QS_watchlistDataManager.getNameById(id);
    },
    _getSortMenuData:function(){
        var operateMenuData_Sort = this.core.getSortColumns();
        var lastSortCellKey = this.core.getlastSortCellKey();
        for (var i in operateMenuData_Sort) {
            operateMenuData_Sort[i].selected = operateMenuData_Sort[i].val == lastSortCellKey;
            operateMenuData_Sort[i].type == "ratio";
        }
        return operateMenuData_Sort;
    },
    _getOperateMenuData: function(id,myViewList){
        id = id || this.profile.currentId;
        var type = QS_watchlistDataManager.getTypeById(id),qslan=QS_Lang.watchlist;//def to current watchlist
        var permission = QS_watchlistDataManager.getPermissionById(id); //0readonly, 1write
        var sourceType = QS_watchlistDataManager.getSourceById(id);
        var operateMenuData_Sort = this._getSortMenuData();
        var needDisable = this.core.getDisplayLayout()=="heatmap"
        return [{
            txt: type == 0 ? qslan["pl"] :  qslan["wl"],
            val: '',
            className: 'subtitle'
        }, permission == 0 ? null : {
            txt: qslan["save"],
            val: 'save'
        }, permission == 0 || this.profile.isDotComUser? null : {
            txt: qslan["rename"],
            val: 'rename'
        }, (id == -7 || id == -8 || sourceType == 'LPLH' || sourceType == 'LPLP') ? null : { //disbale saveas for Future/Forex
            txt: qslan["saveas"],
            val: 'saveas'
        }, (permission == 0 || !this.profile.editdialog)? null : {
            txt: qslan["edit"],
            val: 'edit'
        }, permission == 0 ? null : {
            txt: qslan["delete"],
            val: 'del'
        }, !this.profile.startup ? null : {
            txt: qslan["startupname"],
            val: 'change'
        }, {
            type: "separator"
        }, {
            txt: qslan["columnview"],
            val: '',
            className: 'subtitle'
        }, {
            txt: qslan["sort"],
            val: 'sort',
            subMenu: operateMenuData_Sort
        }, {
            txt: qslan["edit"],
            val: 'cv_edit',
            disable: needDisable
        }, {
            txt: qslan["ms_views"],
            val: 'ms_view',
            disable: needDisable,
            subMenu: this.operateMenuData_MSView
        }, {
            txt: qslan["my_views"],
            val: 'my_view',
            disable: needDisable,
            subMenu: myViewList
        }];
    },
	openConstituents:function(name,data){
		var self=this;
		self.showLoading(true);
		QS_watchlistDataManager.createTempWatchList(name,[], function(d){
            self._insertTabitem(d.portfolioId, name);
			self.acceptTicker(data.pids,true);
			self.hideLoading();
        });
	},
    _rebindOperateMenu: function(tab){  // rebind the customize views.  
        var self = this,qslang=QS_Lang.watchlist;
        if (tab) {
            QS_CustomViewManagement.getCustomviewList(function(o){  // get the customize view
                var myView = [], ischanged = false;
                //self.operateMenuData_MyView = [];
                var selectViewId = self.profile.colsViewID;
                for (var i = 0; i < o.length; i++) {
                	if(i < self.profile.viewCount){
	                    myView.push({
	                        txt: o[i].title,
	                        val: o[i].id,
	                        vid: o[i].id,
	                        type: "ratio",
	                        selected: selectViewId == o[i].id
	                    });
	                }else{
	                	myView.push({
			                type: "separator"
			            }, {
			                txt: qslang["vmsub_more"],
			                val: -1,
			                o: 'more'
			            });
			            break;
	                }
                }
                if (myView.length > 0) {
                    myView.push({
                        type: 'separator'
                    });
                }
                myView.push({
                    txt: qslang["new_views"],
                    val: -1,
                    o: 'cv_add'
                });
                var activeId=tab.id;
                var menuData = self._getOperateMenuData(activeId,myView);
                self.operatemenu.reBind(menuData);
                if(selectViewId<0){  // select the view id in MS view
                    self.operatemenu.changeUIState(selectViewId,"ms_view",true);
                }
				var position=self.tabmenu.currentTab.menu.position();
                self.operatemenu.setPosition(position.left + 1, position.top + 46);
                self.operatemenu._listID = activeId;
                self.operatemenu.show();
            });
        }
    },
    _reBindMore: function(o,click){
		var self=this,qslan=QS_Lang.watchlist,viewData=[];
		for (var i = 0; i < o.length; i++) {
            viewData.push({
                text: o[i].title,
                cmd: o[i].id
            });
        }
        var tab={};
        tab[qslan["dg_titleview"]]=viewData;
        workspaceManager.openOpenFileWin(tab, function(el){
            click(el.getAttribute('cmd'),el.innerText || el.textContent);
        }, null , null);
    },
    _createOperateMenu: function(){ // create the opreate menu and initialize it.
        var self = this;
        this.operatemenu = new Util.CascadeMenu(typeof this.__winObj != 'undefined' ? this.__winObj.toolPanel : this.el.find('.rtq-wl-tab')[0], {
            display: false,
            autoHide: true
        }, this._getOperateMenuData(null,[]), {
            onClick: function(item){
                var type = self.tabmenu.currentTab.type;
                var id=self.tabmenu.currentTab.id;
				var pval = item.parent?item.parent.data.val:null;
				if(item.data.o){//sub menu 
					switch(item.data.o){
						case "more":
		                 	QS_CustomViewManagement.getCustomviewList(function(o){
		                		self._reBindMore(o,function(viewid,name){
		                			self.showLoading(true);
		                			self._changeViewId(viewid,false,function(custom){
										if(custom.id==viewid&&self.profile.setting){
										    self.settingpanel.updateCurrentView(name||custom.data.title,"");
										}
										self.hideLoading();
			                        });
		                		});
		                	});
		                	break;
		                case 'cv_add': // add customiz view
	                        //self.createColsViewPN();
	                        QS_WatchListCustomView.create(null,function(viewId,name){
	                        	self.showLoading(true);
	                            self._changeViewId(viewId,false,function(custom){
	                                if(self.profile.setting&&custom.id==viewId){
	                                    self.settingpanel.updateCurrentView(name,"");
	                                 }
									 self.hideLoading();
	                            }); // after new view ,update the view of this watchlist.
	                        });// create
	                        break;
                    }
            	}else if(!pval){
     				switch (item.data.val) {//level menu
	                	case 'change'://select
	                    	self.showLoading(true);
	                        self._autoSave(self.tabmenu.currentTab.id);
	                        self.tabmenu.removeTab(self.tabmenu.currentTab);
	                        self._startUpShow();
	                        self._changeTitle();
							self.hideLoading();
	                        break;
	                    case 'save':
	                        self.core.saveWatchlist(id);
	                        break;
                        case 'rename':
	                    	self._autoSave(id);
	                        self.core.reNameWatchlist(id,type);
							break;
	                    case 'saveas':
	                    	self._autoSave(id);
	                        self.core.saveAsWatchlist(id, function(id,name){ // open the saved watchlist in a new tab.
	                            self._insertTabitem(id, name);
								if (self.profile.startup) {
									self.startup.refreshList();
								}
	                        });
	                        break;
	                    case 'del':
	                        self.core.deleteWatchlist(id);
	                        break;
	                    case 'edit'://{id:wlid,name:wlname,data:holdings, type: (0:pl,1:wl)}
	                        self._openEditDialog(self.profile.currentId,type);
	                        break;
                        case 'cv_edit': // add the view
	                        if (self.profile.colsViewID < 1 || !self.profile.colsViewID) {
	                            Util.message(QS_Lang.text["watchlistcveditdef"]);
	                            QS_WatchListCustomView.create({cols: self.core.getColumnCfg()},function(viewId,name){ // save as the view
	                                self.showLoading(true);
	                                self._changeViewId(viewId,false,function(custom){
	                                    if(self.profile.setting&&viewId==custom.id){
	                                        self.settingpanel.updateCurrentView(name,"");
	                                     }
										 self.hideLoading();
	                                }); // after new view ,update the view of this watchlist.
	                            });// create
	                            //self.createColsViewPN(self.grid.getColumnCfg());
	                        }else {
	                            var viewId = self.profile.colsViewID
	                            QS_CustomViewManagement.getCustomviewData(viewId, function(custom){
									if(custom.id==viewId){
										QS_WatchListCustomView.edit({
											title: custom.data.title,
											cols: custom.data.cols,
											id: custom.id
										});
									}else{
										Util.message(QS_Lang.text["watchlistcvfailed"]);
									}
	                            });
	                        }
	                        break;
		            }
		        }else{
	                switch (pval){//parent menu
	                    case 'my_view':
	                    	self.showLoading(true);
	                    	var viewid=item.data.val;
	                        self._changeViewId(viewid,false,function(custom){
								if(custom.id==viewid&&self.profile.setting){
								    self.settingpanel.updateCurrentView(item.data.txt,"");
								 }
								 self.hideLoading();
	                        });
	                        break;
	                     case 'ms_view':
	                     	var viewid=item.data.val;
	                     	self.showLoading(true);
	                        self._changeViewId(viewid,false,function(custom){  
	                             if(custom.id==viewid&&self.profile.setting){
	                                 self.settingpanel.updateCurrentView(item.data.txt,"");
	                             }
								 self.hideLoading();
	                         });
	                        break;
	                    case 'sort':
	                        self.core.sort(item.data.val);
	                        break;
	                }
	            }
                self.operatemenu.hide();
            }
        });
    },
    getTabData: function(openedList){
        var d = [];
        if (openedList.length == 0 || typeof openedList[0].id == 'undefined') {  // no opened list
            d .push({
                txt: this._getWatchlistName(this.staticValue.selectTabID),
                id: this.staticValue.selectTabID
            });
        }else{
            var name = '',id=null;
            for (var i = 0; i < openedList.length; i++) {
            	id = openedList[i].id;
            	if(id == this.staticValue.selectTabID){
            		d .push({
		                txt: this._getWatchlistName(this.staticValue.selectTabID),
		                id: this.staticValue.selectTabID
		            });
            	}else{
            		name = this._getWatchlistName(id);
            		if (name && name.length > 0) {
	            		d .push({
			                txt: this._getWatchlistName(id),
			                id: id,
			                type: QS_watchlistDataManager.getTypeById(id)||0
			            });
	            	}
            	}
            }
        }
        return d;
    },
    updateData:function(gKey,needupdatefiled){
    	if(this.core){
	        this.core.updateData(gKey,needupdatefiled);
	    }
    },
    _setCurrentId:function(activeId){
        this.profile.currentId=activeId;
    },
	//Title
	_changeTitle: function(title){
        if (this.profile.setting&&this.settingpanel.saveConfig().isSelectTabName) {
            title = title ? title:this._getWatchlistName(this.staticValue.selectTabID);
            this.setTitle(title);
        }
    },
    // tabmenu
    _buildTabMenu: function(tabData){
        var self = this;
        this.tabmenu = new Util.TabMenu(this.el.find('.rtq-wl-tab')[0], tabData, {
            onActive: function(tab){
				self.showLoading(true);
                var activeId=tab.id;
				self.profile.currentId=activeId;
                self.activeTabId = activeId;
                if (parseInt(activeId) < 0 || activeId==self.staticValue.selectTabID) {//default watchlist can't edit
                    if (self.profile.editdialog) {
						QS_watchlistEditDialog.setCallback(self._editDialogCallback());
                        QS_watchlistEditDialog.hide();
                    }
                }                
				self._changeTitle(tab.txt);
                if (activeId == self.staticValue.selectTabID && self.profile.startup) {
                    self.startup.show();
                    QS_watchlistDataManager.registerWatchlist(self.core, activeId);
					self._displayStartup = true;
					if (!self.startup.ready) {
			            self.startup.refreshList();
			        }
                    self.core.hide();
                    self._changeTitle();
					self.hideLoading();
                }else if (activeId != self.staticValue.selectTabID) {
                    if (self.profile.startup) {
                        self.startup.hide();
                        self._displayStartup = false;
                    }
                    self.core.show();
                    self.core.empty();
                    self.showLoading(true);
                    self.core.openWatchlist(activeId, tab.txt,function(){
                    	/*
                    	if(self.tabmenu){
							self.tabmenu.showActiveTab();
						}
						*/
						//self.hideLoading();
                    });
                }
				if (self.profile.operatemenu) {
					self._bindOperateMenutoTab(tab);
				}
            },
			onAddTab:function(){
				if(self.tabmenu.currentTab){
					self._autoSave(self.tabmenu.currentTab.id);
				}
				self._startUpShow();
			},
            onDeActive: function(tab){
            	var activeID=tab.id;
                if ( activeID== self.staticValue.selectTabID && self.profile.startup) {
                    self.startup.hide();
                    QS_watchlistDataManager.unregisterWatchlist(self.core, activeID);
                    self._displayStartup = false;
                }
                else {
                    self.core.stopSubscribe();
                    self._autoSave(activeID);
                }
                //only active menu display this ddl
                tab.menu.unbind('mouseover.tabddl').unbind('mouseout.tabddl');
            },
            beforeClose: function(tab){
            	var activeID=tab.id;
                if(activeID!=self.staticValue.selectTabID){          
                    self.core.stopSubscribe();
                }
                self._autoSave(activeID);
            },
            afterClose: function(tab){
                if (self.tabmenu.getIdList().length < 1) {
                    self._startUpShow();
                    self._changeTitle();
                }
            },
            afterRearrange: function(tab){
            }
        }, {
            tabsList: true,
            isExcuteCallbackAtInit: true,
            closeAction: 'hide',
            activeTabId: this.profile.currentId||this.staticValue.selectTabID,
            activeTabIndex : this.profile.activeTab,
            autoSlideToActiveTab: true,
			marginRightWidth:26,
			plusSymbol:typeof this.profile.plusSymbol!='undefined'?this.profile.plusSymbol:(this.profile.isAPI?false:true),
            rearrange: true
        });
    },
	_autoSave: function(id){
        if (!id || this._saving || id < 0 || id == this.staticValue.selectTabID) {
            return;
        }
        else {
            QS_watchlistDataManager.saveHoldings(id,null,true);
        }
    },
    _insertTabitem: function(tabid, txt,index){  // insert a tabitem then active it.
        var tabProfile={},tab=null;
        if(tabid!=this.staticValue.selectTabID){//select can duplicate
        	//tab = this.tabmenu.getTabById(tabid);
        	tabProfile = {
                txt: txt,
                id: tabid,
                type: typeof(QS_watchlistDataManager) == "undefined" ? 1 : QS_watchlistDataManager.getTypeById(tabid)
            };
        }else{
        	tabProfile ={
        		txt: txt,
                id: this.staticValue.selectTabID
        	};
        }
        if(!tab){
	        tab = this.tabmenu.addTab(tabProfile,index);
	    }
		tab.active();
    },
    _bindOperateMenutoTab: function(tab){
        var tab = tab || this.tabmenu.currentTab;
        var activeID=tab.id;
        if (activeID == this.staticValue.selectTabID) {
            return
        }else {
            var self = this;
            //will trigger n times when hover or out A, optimize --jacky110214
            tab.menu.unbind('mouseover.tabddl').bind('mouseover.tabddl', function(){
                self._rebindOperateMenu(tab);
            }).unbind('mouseout.tabddl').bind('mouseout.tabddl', function(){
                self.operatemenu.hide();
            });
        }
    },
    _renameTab: function(id, name){
        var tab = this.tabmenu.getTabById(id);
        if (tab) {
            tab.txt = name;
            tab.reName(name);
            this._changeTitle(name);
            this.tabmenu.reBindTabList();
        }
    },
    _removeTabs:function(id,needActiveOther){
		 var tabs = this.tabmenu.getTabsByid(id); 
		 this.tabmenu.removeTabs(tabs,needActiveOther);
    },
    _removeTabitem: function(id,needActiveOther,index){ // id : the id of tabitem.
        var tab = this.tabmenu.getTabById(id);
        if(typeof index!='undefined'){
        	tab = this.tabmenu.getTabByIndex(index);
        }
        if (tab) {
            this.tabmenu.removeTab(tab, needActiveOther);
        }
    },
    getSettingPanelDOM: function(){
        return this.profile.setting ? this.settingpanel.el[0] : null;
    },
    changeOutSize:function(w,h){
		h=h||this.container.parent().height();
		w=w||this.container.width();
		var tickerlistH=h;
		if(this.tabmenu){
			this.tabmenu.reSize();
		}
        if (this.core) {
			this.core.changeOutSize(w,h - (this.profile.isShowSummary ? this.staticValue.sumHeight : 0)-(this.profile.isShowHideChecked? this.staticValue.tabMenuHeight : 0));
        }
        if (this.profile.startup) {
			//when tabmenu hide, the container for displaing startup should be add the height of tabmenu.
            this.startup.resize(w, h-(this.profile.isShowHideChecked? this.staticValue.tabMenuHeight : 0));
		}
    },
    autoCPCallback: function(ticker){  // invork by autocomplete box
		if(this.profile.editdialog&&QS_watchlistEditDialog.getID()==this.profile.currentId){
			QS_watchlistEditDialog.hide();
		}
		if(this.profile.operatemenu){
			this.operatemenu.hide();
		}
		if(this.profile.contextmenu){
			QS_watchlistContextMenu.hide();
		}
        this.acceptTicker(ticker);
    },
    acceptTicker:function(ticker,showAlert){  //
        if(this.activeTabId==0)return false;  // show startup. 
        this.core.addTickers(ticker,showAlert)
    },
    ready: function(){
        GB_DataManager.register(this);
    },
    saveConfig:function(){  // save the profile for watchlist.
        this._autoSave(this.profile.currentId); // save the holdings in current watchlist.
        /* save the watchlist in tabmenu*/
        var id=null,newOpenedList = [],data=this.tabmenu.getIdList();
        for(var i=0,l=data.length;i<l;i++){
         	id=data[i];
        	if(QS_watchlistDataManager.getSourceById(id)=='temp') continue;
            newOpenedList.push({
                "id": id
            });
        }
        var config = {
            currentId: this.profile.currentId,  // the watchlist id is managed by core object.
            activeTab: this.tabmenu.getTabIndex(),
            colsViewID: this.profile.colsViewID,  // the customize view id is managed by watchlist object.
            displayLayout: this.core.getDisplayLayout(),// the displayLayout is managed by tickerList object.
            groupBy: this.core.getGroupBy(),  //the group by field is managed by tickerList object.
            sortCell: this.core.getlastSortCellKey(), // the sort cell field. managed by grid.
            sortOrder: this.core.getSortOrder(),  // the orientation of sort: desc or asc. managed by grid.
            openedList: newOpenedList
            //tempCols: this.core.getDisplayLayout() != 'heatmap' ? null : this._getSavedView(this.core.getViewKeys()) // does not need to sava tempCols config if not in Heatmap mode  
        };
        if(this.profile.setting){
            var stPlusProfile = this.settingpanel.saveConfig();
            config.windowConfig =  stPlusProfile// window tab item.
            config.isShowHideChecked = stPlusProfile.isShowHideChecked;
            //config.savedTitle = "";
            config.isShowSummary = this.profile.isShowSummary;
            if(stPlusProfile.isSelectTabName){
                config.title = this.getTitle();
            }
        }
        return config;
        
    },
	getColumnCfg:function(){
		return this.core.getColumnCfg();
	},
	LPLCustomize: function(id){
        if (this.profile.isLPLUser) {
            var sourceType = QS_watchlistDataManager.getSourceById(id);
            this.settingPnObj.refreshGroupDDL(sourceType);
            if (sourceType == 'LPLP') {
                var groupBy = QS_watchlistDataManager.getLPLGroupBy(id);
				this.changeViewType("listgroup");
				this.groupBy(groupBy,null);
				if (this.profile.setting) {
					this.settingpanel.setTypeDDL("listgroup");
					this.settingPnObj.setGroupDDL(groupBy);
					this.settingPnObj.disableGroupDDL(true);
				}
            }
            else 
                if (sourceType == 'LPLH') {
					this.changeViewType("listgroup");
                    this.groupBy("AccountName");
					if (this.profile.setting) {
						this.settingpanel.setTypeDDL("listgroup");
                        this.settingPnObj.setGroupDDL("AccountName");
                        this.settingPnObj.disableGroupDDL(true);
					}
                }
                else //change to grouping by sector if not LPL watchlist / portfolio
                     if (this.profile.groupBy == 'Household' || this.profile.groupBy == 'AccountName') {
                        this.groupBy('la03z',null);
                    }
        }
    },
	refreshGrid: function(){
        var self = this;
        this.core.openWatchlist(this.profile.currentId, "", null);
    },
    fileMenuCallback: function(val){ // handler the file menu in windows click event.
        var self=this;
        switch (val) {
            case "refresh":
                var id = this.profile.currentId;
                if (id == self.staticValue.selectTabID) {
					if(this.profile.startup&&this.startup){
						this.startup.refreshList();
					}
                }else {
                    this.refreshGrid();
                }
                break;
            case 'import_manual':
            case 'excel':
				if (this.profile.currentId == self.staticValue.selectTabID) {
                    Util.alert(QS_Lang.watchlist["import_excelprompt"]);
                    return;
                }
               	var type = val, self = this;
				QS_watchlistImportor.callBack.reBindCaller(this);
				QS_watchlistDataManager.getHoldings(self.profile.currentId, function(holdings){
					QS_watchlistImportor.open(type, {
						inCurrentList: true,
						currentLen: holdings.length,
						portfolioId: self.profile.currentId
					});
				});
			    break;
            case "export":
				if (this.profile.currentId== self.staticValue.selectTabID) {
                    Util.alert(QS_Lang.watchlist["import_excelprompt"]);
                    return;
                }
				
				var self = this, currentID = this.profile.currentId;
				QS_watchlistDataManager.getHoldings(currentID, function(holdings){

					var data = [], cols = self.core.getSortColumns(), domMap = self.core.tickerList.grid.DOMMap;
					for (var i = 0, len = holdings.length; i < len; i++) {
						var d = {}, holdingId = holdings[i]["HldgId"];
						for (var idx = 0; idx < cols.length; idx++) {
							var dataIndex = cols[idx].val,  
								header = cols[idx].txt.replace(/<[^>]*>/ig, ''),
								field = dataIndex.indexOf("%") != -1 ? dataIndex.replace(/%/g, '^__^') : dataIndex; 
								//dataIndex.indexOf("^__^") != -1 ? dataIndex.replace(/\^__\^/g, '%') : dataIndex;
							
							if (' M* Rating ___ Up/Down ___ Alert '.indexOf(header) != -1) {
								continue;
							}
							if(field == "Chg^__^"){
								var dom = domMap[holdingId]['Chg%'];
								var txt = dom.innerText ? dom.innerText : dom.textContent;
								d[field] = (!!txt ? txt : "");
								continue;
							}
							
							if (field == 'Up/Down') {
								d[field] = ""
							}
							else {
								if (typeof(domMap[holdingId]) == 'undefined' 
									|| typeof(domMap[holdingId][field]) == 'undefined' 
									|| !domMap[holdingId][field] 
									|| domMap[holdingId][field] == null) {
									d[field] = "";
								}
								else {
									var dom = domMap[holdingId][field];
									var txt = dom.innerText ? dom.innerText : dom.textContent;
									d[field] = (!!txt ? txt : "");
								}
								
							}
						}
						data.push(d);
					}
					QS_watchlistDataExporter.exportData(cols, data, {
						name: self.tabmenu.currentTab.txt,
						currentID: currentID,
						currentType: QS_watchlistDataManager.getTypeById(currentID),
						currentSrc: QS_watchlistDataManager.getSourceById(currentID)
					});
				});
                break;
        }
    }
});
